﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using LibraryMusicStore;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.DXErrorProvider;

namespace AppMusicStore
{
    public partial class frmGenreEditor : DevExpress.XtraEditors.XtraForm
    {
        IRepository<Genre> genreRepository;
        internal int? id;

        internal IRepository<Genre> GenreRepository 
        {
            get { return genreRepository; }
            set { genreRepository = value; }
        }

        public frmGenreEditor()
        {
            InitializeComponent();
        }

        private void frmAlbumEditor_Load(object sender, EventArgs e)
        {
            try
            {
                //RetriveData();

                if (id != null)
                    InitGenre();
                else
                    this.layoutId.HideToCustomization();

                btnCancel.CausesValidation = false;
            }
            catch (Exception)
            {
                this.Close();
                throw;
            }
        }

        private void RetriveData()
        {
            try
            {
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void InitGenre()
        {
            try
            {
                lblId.Text = "Số loại: " + id;

                var genre = genreRepository.GetById((int)id);
                //db.Albums.Single(a => a.AlbumId == id);

                txtName.Text = genre.Name;
                txtDescription.Text = genre.Description;
            }
            catch (Exception)
            {
                throw;
            }
        }

        #region "Button click"
        private void btnAccept_Click(object sender, EventArgs e)
        {
            //validate control
            this.ValidateChildren();

            if (ErrorProvider1.HasErrors)
            {
                foreach (var item in ErrorProvider1.GetControlsWithError())
                {
                    item.Focus();
                    Common.ShowErrorBox(ErrorProvider1.GetError(item));
                    return;
                }
            }

            //switch
            if (id != null)
                Edit();
            else
                Insert();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                if (id != null)
                {
                    var genre = genreRepository.GetById((int)id);
                        //Common.GetAlbumById(id, db);
                    if (CheckDiff(genre))
                    {
                        DialogResult rs = Common.ShowQuestionBox("Lưu thay đổi ? ", "yesnocancel");
                        if (rs == DialogResult.Yes)
                            btnAccept.PerformClick();
                        else if (rs == DialogResult.Cancel)
                            return;
                    }
                }
            }
            catch (Exception)
            {
                this.Close();
                throw;
                //Common.ShowErrorBox(ex.Message);
            }
            this.Close();
        }
        #endregion

        #region Insert, Edit ...
        private void Edit()
        {
            try
            {
                var genre = genreRepository.GetById((int)id);
                    //Common.GetAlbumById(id, db);
                if (!CheckDiff(genre))
                {
                    this.Close();
                    return;
                }
                if (genre.Name != txtName.Text.Trim())
                {
                    //duplicate name
                    if (genreRepository.Duplicate(a => a.Name.ToUpper()
                                .Contains(txtName.Text.ToUpper().Trim())))
                    {
                        Common.ShowErrorBox("Tên loại đã có");
                        txtName.Focus();
                        return;
                    }
                }

                DialogResult result = Common.ShowQuestionBox(
                    "Số loại: " + id + "\n" +
                    "Sửa ?", "okcancel");

                if (result == DialogResult.OK)
                {
                    InitNewGenre(genre);
                    genreRepository.SubmitChanges();
                    //db.SubmitChanges();

                    Common.ShowInfomationBox("Sửa thành công");

                    this.DialogResult = DialogResult.OK;
                }

            }
            catch (Exception )
            {
                //Common.ShowErrorBox(ex.Message);
                this.Close();
                throw;
            }
        }

        private bool CheckDiff(Genre genre)
        {
            if (genre.Name != txtName.Text.Trim()
                ||genre.Description != txtDescription.Text.Trim())
            {
                return true;
            }

            return false;
        }

        private void InitNewGenre(Genre genre)
        {
            try
            {
                genre.Name = txtName.Text.Trim();
                genre.Description = txtDescription.Text.Trim();
                
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void Insert()
        {
            try
            {
                var genre = new Genre();
                //duplicate name
                if (genreRepository.Duplicate(a => a.Name.ToUpper()
                            == txtName.Text.ToUpper().Trim()))
                {
                    Common.ShowErrorBox("Tên loại đã có");
                    txtName.Focus();
                    return;
                }

                //create new genre object
                InitNewGenre(genre);

                //insert into database
                genreRepository.InsertOnSubmit(genre);
                genreRepository.SubmitChanges();
                //db.Albums.InsertOnSubmit(genre);
                //db.SubmitChanges();
                
                
                Common.ShowInfomationBox("Thêm thành công loại " + genre.Name);

                this.DialogResult = DialogResult.OK;
            }
            catch (Exception)
            {
                //Common.ShowErrorBox(ex.Message);
                this.Close();
                throw;
            }
        }
        #endregion

        private void Check(object sender, CancelEventArgs e)
        {
            string str = null;
            
            //title required
            if (sender.GetType().Name == "TextEdit")
            {
                TextEdit txt = (TextEdit)sender;
                if (txt.Text.Trim().Length == 0)
                    str = "Chưa nhập tên loại";
            }

            ErrorProvider1.SetIconAlignment((Control)sender, ErrorIconAlignment.MiddleRight);
            ErrorProvider1.SetError((Control)sender, str);
        }
    }
}